// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL + '/api';

// 获取token
const getToken = () => {
  return localStorage.getItem('admin_token');
};

// 通用请求函数
async function request(url, options = {}) {
  try {
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers,
    };

    // 如果是需要认证的请求，添加token
    const token = getToken();
    if (token && (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE')) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    const response = await fetch(`${API_BASE_URL}${url}`, {
      ...options,
      headers,
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || '请求失败');
    }

    return await response.json();
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
}

// ============ 设置 API ============

const settingsAPI = {
  // 获取工作区默认设置
  getWorkspaceDefaults: () => request('/settings/workspace-defaults'),

  // 更新工作区默认设置
  updateWorkspaceDefaults: (data) => request('/settings/workspace-defaults', {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
};

export default settingsAPI;

